package com.ruoyi.sumfun.blog.tool.file.service.Impl;

import com.alibaba.nacos.common.utils.IoUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;

import com.ruoyi.sumfun.blog.tool.file.config.MinioConfig;
import com.ruoyi.sumfun.blog.tool.file.service.IMinioSysFileService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Minio 文件存储
 *
 * @author ruoyi
 */
@Service
public class MinioSysFileServiceImpl implements IMinioSysFileService {
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;

//    @Autowired
//    private PdfUtils pdfUtils;
//
//    @Autowired
//    private FileUploaderUtils  fileUploaderUtils;

    private static final String shuiyin = "EvaluationWarning:ThedocumentwascreatedwithSpire.PDFforJava.";

    /**
     * Minio文件上传接口
     *
     * @param inputStream 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(String fileName, InputStream inputStream, Long fileSize, String ContentType) throws Exception {
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .stream(inputStream, fileSize, -1)
                .contentType(ContentType)
                .build();
        client.putObject(args);
        IoUtils.closeQuietly(inputStream);
        return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
    }

    @Override
    public String uploadPDF(String fileName, MultipartFile file) throws Exception {
//        String caseName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
//        if (caseName.equals("docx") || caseName.equals("doc")|| caseName.equals("xlsx") || caseName.equals("xls") || caseName.equals("ppt") || caseName.equals("pptx")) {
//
//            String filename = file.getOriginalFilename();
//            String urlFileName = fileUploaderUtils.getRandomFileName(FileUploaderUtils.getSuffix(filename));
//            String originalUrl = fileUploaderUtils.upload(file.getBytes(), urlFileName);
//             pdfUtils.toPdf(fileName,pdfUtils.getServerPath(originalUrl), pdfUtils.getTargetFolder(originalUrl));
//             if (urlFileName.contains("\\")){
//                 urlFileName=urlFileName.substring(urlFileName.lastIndexOf("\\")+1,urlFileName.lastIndexOf("."))+".pdf";
//             }else {
//                 urlFileName=urlFileName.substring(urlFileName.lastIndexOf("/")+1,urlFileName.lastIndexOf("."))+".pdf";
//             }
//            return fileName.substring(0,fileName.lastIndexOf("/"))+"/" +urlFileName;
//
//        }else  {
//
//            return FileConvertUtils.getConver(fileName, minioConfig.getBucketName(), minioConfig.getMinioClient(), file);
//        }
        return "";
    }


    @Override
    public InputStream downloadFile(String originalName, HttpServletResponse response) {
        try {
            MinioClient minioClient = minioConfig.getMinioClient();
            InputStream file = minioClient.getObject(GetObjectArgs.builder().bucket(minioConfig.getBucketName()).object(originalName).build());

            String filename = new String(originalName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
            if (StringUtils.isNotBlank(originalName)) {
                filename = originalName;
            }
            //response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename.substring(filename.lastIndexOf("/") + 1), "UTF-8"));
            /*response.setContentType("application/octet-stream");*/
            response.setCharacterEncoding("UTF-8");
            ServletOutputStream servletOutputStream = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = file.read(buffer)) > 0) {
                servletOutputStream.write(buffer, 0, len);
            }
            servletOutputStream.flush();
            file.close();
            servletOutputStream.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public AjaxResult viewStream(String originalName, HttpServletResponse response) {
        AjaxResult ajaxResult = new AjaxResult();
        InputStream inStream = null;

        try {
            MinioClient minioClient = minioConfig.getMinioClient();
            inStream = minioClient.getObject(GetObjectArgs.builder().bucket(minioConfig.getBucketName()).object(originalName).build());
            /* InputStream inStream = FileConvertUtils.getConver(originalName,minioConfig.getBucketName(),minioClient);*/
            String originalNames = originalName.substring(0, originalName.lastIndexOf("/") + 1);
            String filename = new String(originalNames.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
            if (StringUtils.isNotBlank(originalName)) {
                filename = originalNames;
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename.substring(filename.lastIndexOf("/") + 1), "UTF-8"));
            /*            response.setContentType("application/octet-stream");*/
            response.setCharacterEncoding("UTF-8");
            ServletOutputStream servletOutputStream = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = inStream.read(buffer)) > 0) {
                servletOutputStream.write(buffer, 0, len);
            }
            servletOutputStream.flush();
            inStream.close();
            servletOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ajaxResult.put("data", inStream);
    }

    @Override
    public InputStream batchDownload(Map<String, Object> map, HttpServletResponse response) {
//        ByteArrayOutputStream outputStream = docConverUtils.changeDoc(map);
//        InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
//        try {
//            String filename = (String) map.get("fileName") + ".doc";
//            //response.setHeader("Content-Disposition", "attachment;filename=" + filename);
//            filename = new String(filename.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
//            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename));
//            response.setContentType("application/octet-stream");
//            response.setCharacterEncoding("UTF-8");
//            ServletOutputStream servletOutputStream = response.getOutputStream();
//            int len;
//            byte[] buffer = new byte[1024];
//            while ((len = inputStream.read(buffer)) > 0) {
//                servletOutputStream.write(buffer, 0, len);
//            }
//            servletOutputStream.flush();
//            inputStream.close();
//            servletOutputStream.close();
//        } catch (Exception e) {
//            System.out.println(e);
//        }
//        return inputStream;
//    }
        return null;
    }
}
